# -*- coding: utf-8 -*-
__author__ = 'liubei'

from mongoengine import *
import time
import aes
import schedule
import logging
from mongolog.handlers import MongoHandler
import sms
import db_engine

diffUnit = 3

host = db_engine.host

handler = MongoHandler.to(host=db_engine.host, db='mongolog', collection='log')
logger = logging.getLogger('survey')
logger.setLevel(logging.INFO)
logger.addHandler(handler)

class SurveySchedule(DynamicDocument):
    userPhone = StringField(required=True)
    lastSurvey = StringField(required=True)
    currentSurvey = StringField(required=True)
    nextSurvey = StringField(required=True)
    firstDone = IntField(required=True)
    lastDone = IntField(required=True)


class SurveyLog(DynamicDocument):
    userPhone = StringField(required=True)
    day = IntField(required=True)
    status = IntField(required=True, default=False)
    createDate = IntField(required=True)
    survey = StringField(required=True)


class SurveyStrategy(DynamicDocument):
    day = IntField(required=True)
    survey = StringField
    last = StringField
    next = StringField
    start = IntField
    end = IntField


class SurveySmsLog(DynamicDocument):
    userPhone = StringField(required=True)
    log = StringField(required=True)
    createDate = IntField(required=True)


def querySurveySchedule(userPhone):
    connect('az', host=host)
    results = SurveySchedule.objects(userPhone=userPhone)
    aes_cipher = aes.AESCipher(aes.aes_key)
    if results.count() == 0:
        surveyStrategy = SurveyStrategy.objects(start=1)[0]
        surveySchedule = SurveySchedule(lastSurvey=aes_cipher.encrypt(surveyStrategy.last),
                                        currentSurvey=aes_cipher.encrypt(surveyStrategy.survey),
                                        nextSurvey=aes_cipher.encrypt(surveyStrategy.next),
                                        userPhone=userPhone, firstDone=0, lastDone=0)
        surveySchedule.save()
    else:
        surveySchedule = results.first()
    return surveySchedule


def querySurveySmsLog(userPhone):
    connect('az', host=host)
    results = SurveySmsLog.objects(userPhone=userPhone).order_by('-createDate')
    if results.count() == 0:
        surveySmsLog = SurveySmsLog(userPhone=userPhone, createDate=0, log='')
    else:
        surveySmsLog = results[0]
    return surveySmsLog


def updateSurveySchedule(userPhone, surveyName):
    connect('az', host=host)
    surveySchedule = querySurveySchedule(userPhone)
    surveySchedule.lastDone = int(time.time())
    dayInterval = (surveySchedule.lastDone - surveySchedule.firstDone)/(24*60*60)
    if dayInterval == 0 or surveySchedule.firstDone == 0:
        dayInterval = 0
        if surveyName == "LSQ-V1":
            surveySchedule.firstDone = int(time.time())
            SurveySchedule.objects(userPhone=userPhone).update(set__firstDone=surveySchedule.firstDone)
    elif 4*7+diffUnit >= dayInterval > 0:
        dayInterval = 4
    elif 8*7 + diffUnit >= dayInterval > 4*7+diffUnit:
        dayInterval = 8
    elif 12*7 + diffUnit >= dayInterval > 8*7+diffUnit:
        dayInterval = 12
    elif 16*7 + diffUnit >= dayInterval > 12*7+diffUnit:
        dayInterval = 16
    elif 20*7 + diffUnit >= dayInterval > 16*7+diffUnit:
        dayInterval = 20
    elif dayInterval > 20*7+diffUnit:
        dayInterval = 24
    aes_cipher = aes.AESCipher(aes.aes_key)
    SurveySchedule.objects(userPhone=userPhone).update(set__lastDone=surveySchedule.lastDone)
    if SurveyLog.objects(userPhone=userPhone).count() == 0:
        SurveyLog(userPhone=userPhone, day=dayInterval, status=1, survey=aes_cipher.encrypt(surveyName), createDate=int(time.time())).save()
    else:
        SurveyLog.objects(userPhone=userPhone).update(set__day=dayInterval, set__survey=aes_cipher.encrypt(surveyName), set__status=1)
    checkSurveySchedule(needSendMsg=False)


def updateSurveyScheduleByFirstDone(userPhone, firstDone, lastDone):
    connect('az', host=host)
    SurveySchedule.objects(userPhone=userPhone).update(set__firstDone=firstDone, set__lastDone=lastDone)


def calDayInterval(start, end):
    dayInterval = abs(end - start)/(24*60*60)
    if dayInterval == 0 or start == 0:
        dayInterval = 0
    elif 4*7+diffUnit >= dayInterval > 0:
        dayInterval = 4
    elif 8*7 + diffUnit >= dayInterval > 4*7+diffUnit:
        dayInterval = 8
    elif 12*7 + diffUnit >= dayInterval > 8*7+diffUnit:
        dayInterval = 12
    elif 16*7 + diffUnit >= dayInterval > 12*7+diffUnit:
        dayInterval = 16
    elif 20*7 + diffUnit >= dayInterval > 16*7+diffUnit:
        dayInterval = 20
    elif dayInterval > 20*7+diffUnit:
        dayInterval = 24
    return dayInterval


def calDayIntervalForExport(start, end):
    dayInterval = (end - start)/(24*60*60)
    if dayInterval == 0 or start == 0:
        dayInterval = 0
    elif 4*7-diffUnit > dayInterval > 0:
        dayInterval = 3
    elif 8*7 - diffUnit > dayInterval >= 4*7-diffUnit:
        dayInterval = 7
    elif 12*7 - diffUnit > dayInterval >= 8*7-diffUnit:
        dayInterval = 11
    elif 16*7 - diffUnit > dayInterval >= 12*7-diffUnit:
        dayInterval = 15
    elif 20*7 - diffUnit > dayInterval >= 16*7-diffUnit:
        dayInterval = 19
    elif 24*7 - diffUnit > dayInterval >= 20*7-diffUnit:
        dayInterval = 23
    elif dayInterval >= 24*7-diffUnit:
        dayInterval = 24
    return dayInterval


def checkSurveySchedule(needSendMsg=True):
    aes_cipher = aes.AESCipher(aes.aes_key)
    now = int(time.time())
    connect('az', host=host)
    results = SurveySchedule.objects()
    for surveySchedule in results:
        #未激活问卷RAQ (LSQ-V1和BMQ必须完成才算激活)
        if surveySchedule.firstDone == 0:
            dayInterval = 0
        else:
            dayInterval = calDayInterval(surveySchedule.firstDone, now)
        surveyLogs = SurveyLog.objects(userPhone=surveySchedule.userPhone, day=dayInterval)
        if surveyLogs.count() > 0:
            surveyLogSurvey = aes_cipher.decrypt(surveyLogs[0].survey)
            if surveyLogSurvey == "LSQ-V1":
                surveySchedule.lastSurvey = aes_cipher.encrypt('LSQ-V1')
                surveySchedule.currentSurvey = aes_cipher.encrypt('')
                surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
            elif surveyLogSurvey == "BMQ-G":
                if dayInterval >= 20:
                    surveySchedule.lastSurvey = aes_cipher.encrypt('BMQ-G')
                    surveySchedule.currentSurvey = aes_cipher.encrypt('LSQ-V2')
                    surveySchedule.nextSurvey = aes_cipher.encrypt('')
                else:
                    #完成 第一次 bmq
                    surveySchedule.lastSurvey = aes_cipher.encrypt('BMQ-G')
                    surveySchedule.currentSurvey = aes_cipher.encrypt('LSQ-V1')
                    surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
            elif surveyLogSurvey == "RAQ":
                if dayInterval == 24:
                    day = int(surveyLogs[0].day)
                    if day == 24:
                        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
                        surveySchedule.currentSurvey = aes_cipher.encrypt('BMQ-G')
                        surveySchedule.nextSurvey = aes_cipher.encrypt('LSQ-V2')
                        logger.info(surveySchedule.userPhone + ' second BMQ-G')
                    else:
                        #完成最后一次 即第六次 RAQ
                        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
                        surveySchedule.currentSurvey = aes_cipher.encrypt('')
                        surveySchedule.nextSurvey = aes_cipher.encrypt('BMQ-G')
                        logger.info(surveySchedule.userPhone + ' BMQ-G RAQ')
                else:
                    surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
                    surveySchedule.currentSurvey = aes_cipher.encrypt('')
                    surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
            elif surveyLogSurvey == "LSQ-V2":
                #全部结束
                surveySchedule.lastSurvey = aes_cipher.encrypt('LSQ-V2')
                surveySchedule.currentSurvey = aes_cipher.encrypt('')
                surveySchedule.nextSurvey = aes_cipher.encrypt('')

            SurveySchedule.objects(userPhone=surveySchedule.userPhone).update(set__lastSurvey=surveySchedule.lastSurvey,
                                                                              set__currentSurvey=surveySchedule.currentSurvey,
                                                                            set__nextSurvey=surveySchedule.nextSurvey)
        elif surveySchedule.firstDone == 0:
            continue
        else:
            surveyLogs = SurveyLog.objects(userPhone=surveySchedule.userPhone)
            day = 0
            if surveyLogs.count() > 0:
                day = int(surveyLogs[0].day)
            updateRaq(now, surveySchedule, aes_cipher, day, needSendMsg=needSendMsg)
            SurveySchedule.objects(userPhone=surveySchedule.userPhone).update(set__lastSurvey=surveySchedule.lastSurvey,
                                                                          set__currentSurvey=surveySchedule.currentSurvey,
                                                                          set__nextSurvey=surveySchedule.nextSurvey)


def updateRaq(now, surveySchedule, aes_cipher, day, needSendMsg=True):
    strategyList = (4, 8, 12, 16, 20)
    #
    inter = 1*24*60*60
    oneDay = 1*24*60*60
    diffTime = diffUnit*24*60*60
    oneWeek = 7*24*60*60
    #25 ~ 31
    if 4*oneWeek - diffTime <= now - surveySchedule.firstDone < 4*oneWeek + diffTime:
        surveySchedule.lastSurvey = aes_cipher.encrypt('LSQ-V1')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
        logger.info(surveySchedule.userPhone + ' first RAQ')
    # 53 ~ 59
    elif 8*oneWeek - diffTime <= now - surveySchedule.firstDone < 8*oneWeek + diffTime:
        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
        logger.info(surveySchedule.userPhone + ' second RAQ')
    # 81 ~ 87
    elif 12*oneWeek - diffTime <= now - surveySchedule.firstDone < 12*oneWeek + diffTime:
        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
        logger.info(surveySchedule.userPhone + ' third RAQ')
    # 109 ~ 115
    elif 16*oneWeek - diffTime <= now - surveySchedule.firstDone < 16*oneWeek + diffTime:
        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
        logger.info(surveySchedule.userPhone + ' forth RAQ')
    # 137 ~ 143
    elif 20*oneWeek - diffTime <= now - surveySchedule.firstDone < 20*oneWeek + diffTime:
        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('RAQ')
        logger.info(surveySchedule.userPhone + ' fifth RAQ')
    # 165 ~ ?
    elif 24*oneWeek - diffTime <= now - surveySchedule.firstDone:
        surveySchedule.lastSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.currentSurvey = aes_cipher.encrypt('RAQ')
        surveySchedule.nextSurvey = aes_cipher.encrypt('BMQ-G')
        logger.info(surveySchedule.userPhone + ' six RAQ')
    else:
        surveySchedule.currentSurvey = aes_cipher.encrypt('')
        logger.info(surveySchedule.userPhone + ' not in' +
                    ' day: ' + str((now - surveySchedule.firstDone)/60/60/24) +
                    " curr:" + aes_cipher.decrypt(surveySchedule.currentSurvey))

    #是否需要进行发送短信
    if needSendMsg:
        print 'check send sms'
        surveySmsLog = querySurveySmsLog(surveySchedule.userPhone)
        for i in strategyList:
            if i == 20:
                #查看是否已经发过sms消息 查看是否已经完成
                if day > i:
                    #已经完成
                    print '%s survey have done' % surveySmsLog.userPhone
                elif now - surveySmsLog.createDate < oneDay:
                    #判断当天是否已经发送过短信
                    print '%s survey have send at %s' % (surveySmsLog.userPhone, surveySmsLog.createDate)
                elif not aes_cipher.decrypt(surveySchedule.currentSurvey) == '':
                    sendSms(surveySchedule)
            else:
                #查看是否在区间范围内 eg 25~31  [25 27 29 31]
                if i*oneWeek - diffTime <= now - surveySchedule.firstDone < i*oneWeek - diffTime + inter \
                        or i*oneWeek - inter <= now - surveySchedule.firstDone < i*oneWeek \
                        or i*oneWeek + inter <= now - surveySchedule.firstDone < i*oneWeek + 2*inter \
                        or i*oneWeek + diffTime <= now - surveySchedule.firstDone < i*oneWeek + diffTime + inter:
                    #查看是否已经发过sms消息 查看是否已经完成
                    if day == i:
                        #已经完成
                        print '%s survey have done' % surveySmsLog.userPhone
                    elif now - surveySmsLog.createDate < oneDay:
                        #判断当天是否已经发送过短信
                        print '%s survey have send at %s' % (surveySmsLog.userPhone, surveySmsLog.createDate)
                    elif not aes_cipher.decrypt(surveySchedule.currentSurvey) == '':
                        sendSms(surveySchedule)


def sendSms(surveySchedule):
    # print 'send sms'
    # aes_cipher = aes.AESCipher(aes.aes_key)
    # sms_text = "#survey#=" + aes_cipher.decrypt(surveySchedule.currentSurvey)
    # if not sms_text == '':
    #     logger.info(sms.tpl_send_sms(689651, sms_text, surveySchedule.userPhone))
    #     SurveySmsLog(userPhone=surveySchedule.userPhone, createDate=int(time.time()), log=sms_text).save()
    #==== close ====
    pass


def bmqg():
    connect('az', host=host)
    surveyPage8 = db_engine.SurveyPage(content="如果医生能够增加为每名患者提供的就诊时间，则将开更少的药物。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"]).save()
    surveyPage7 = db_engine.SurveyPage(content="医生太过于相信药物的作用。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage8.id)]).save()
    surveyPage6 = db_engine.SurveyPage(content="是药三分毒。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage7.id)]).save()
    surveyPage5 = db_engine.SurveyPage(content="药物对人体的伤害比大于人从中的获益。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage6.id)]).save()
    surveyPage4 = db_engine.SurveyPage(content="自然疗法比药物疗法更安全。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage5.id)]).save()
    surveyPage3 = db_engine.SurveyPage(content="大部分药物具有成瘾性。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage4.id)]).save()
    surveyPage2 = db_engine.SurveyPage(content="患者应偶尔停止服用药物一段时间。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage3.id)]).save()
    surveyPage1 = db_engine.SurveyPage(content="医生开药太多。", choices=["非常同意", "同意", "不确定", "反对", "强烈反对"], nextIds=[str(surveyPage2.id)]).save()
    db_engine.Survey(firstNode=str(surveyPage1.id), name="BMQ-G", des="服药信念问卷", surveies=[surveyPage1, surveyPage2, surveyPage3, surveyPage4, surveyPage5, surveyPage6, surveyPage7, surveyPage8]).save()


def lsqv1():
    connect('az', host=host)
    surveyPage3 = db_engine.SurveyPage(content="以下哪条与您的情况相符？", choices=["我最近一直吸烟", "我正努力戒烟", "我已戒烟", "我从不吸烟"]).save()
    surveyPage2 = db_engine.SurveyPage(content="我定期锻炼", choices=["完全同意", "不完全同意", "不同意", "不适用"], nextIds=[str(surveyPage3.id)]).save()
    surveyPage1 = db_engine.SurveyPage(isStart=1, content="我饮食健康", choices=["完全同意", "不完全同意", "不同意", "不适用"], nextIds=[str(surveyPage2.id)]).save()
    db_engine.Survey(firstNode=str(surveyPage1.id), name="LSQ-V1", des="生活方式调查问卷--访视1", surveies=[surveyPage1, surveyPage2, surveyPage3]).save()


def lsqv2():
    connect('az', host=host)
    surveyPage3 = db_engine.SurveyPage(content="以下哪条与您的情况相符？", choices=["我最近一直吸烟", "我正努力戒烟", "我已戒烟", "我从不吸烟"]).save()
    surveyPage2 = db_engine.SurveyPage(content="与刚开始参加本研究时相比，我加强了锻炼。", choices=["完全同意", "不完全同意", "不同意", "不适用"], nextIds=[str(surveyPage3.id)]).save()
    surveyPage1 = db_engine.SurveyPage(isStart=1, content="与刚开始参加本研究时相比，我的饮食更加健康。", choices=["完全同意", "不完全同意", "不同意", "不适用"], nextIds=[str(surveyPage2.id)]).save()
    db_engine.Survey(firstNode=str(surveyPage1.id), name="LSQ-V2", des="生活方式调查问卷--访视2", surveies=[surveyPage1, surveyPage2, surveyPage3]).save()


def dotq():
    connect('az', host=host)
    surveyPage1a1 = db_engine.SurveyPage(content="在最后一次就诊时，您持续服用了多少天的可定治疗？", choices=[1, 28], type=2).save()
    surveyPage1a = db_engine.SurveyPage(content="最近一次看医生并得到你的处方药可定是什么时候？", choices=[], type=1, nextIds=[str(surveyPage1a1.id)]).save()


    surveyPage1bbb4 = db_engine.SurveyPage(content="您认为服用可定药物带来的益处超过害处吗？", choices=["否，一点也不", "部分", "是，完全"], nextIds=[]).save()
    surveyPage1bbb3 = db_engine.SurveyPage(content="您理解您为什么在服用可定药物吗？", choices=["不理解，一点也不理解", "部分理解", "是，完全理解"], nextIds=[str(surveyPage1bbb4.id)]).save()
    surveyPage1bbb2 = db_engine.SurveyPage(content="您是否发现不方便或难于遵守可定药物治疗计划？", choices=["否，一点也不", "有点", "是，非常"], nextIds=[str(surveyPage1bbb3.id)]).save()
    surveyPage1bbb1 = db_engine.SurveyPage(content="您是否曾经有记住服用可定药物的问题？", choices=["否，从不", "有时", "是，经常"], nextIds=[str(surveyPage1bbb2.id)]).save()

    #CAQ-4
    surveyPage1bbb = db_engine.SurveyPage(content="如果你有时不服可定药物，您认为这有害吗？", choices=["否", "是"], nextIds=[str(surveyPage1bbb1.id)]).save()


    surveyPage1bba2 = db_engine.SurveyPage(content="您故意不服用可定的频率如何？", choices=["从不", "有时", "经常"], nextIds=[str(surveyPage1bbb.id)]).save()
    surveyPage1bba1 = db_engine.SurveyPage(content="您忘记服用可定的频率如何？", choices=["从不", "有时", "经常"], nextIds=[str(surveyPage1bba2.id)]).save()


    #todo:
    #CAQ_1_NO
    surveyPage1bba = db_engine.SurveyPage(content="当你在过去4周内没有服用可定药物时，", choices=[], nextIds=[str(surveyPage1bba1.id)], type=3).save()

    surveyPage1bb = db_engine.SurveyPage(content="在过去的4周内，您是否每天服用可定药片？", choices=["否", "是"], nextIds=[str(surveyPage1bbb.id), str(surveyPage1bba.id)]).save()
    surveyPage1ba = db_engine.SurveyPage(content="", choices=["我自己主动停用。", "我医生告诉我停用的。"]).save()
    surveyPage1b = db_engine.SurveyPage(content="您是否已经停止服用可定药物？", choices=["否", "是"], nextIds=[str(surveyPage1bb.id), str(surveyPage1ba.id)]).save()

    #DoTQ_1
    surveyPage1 = db_engine.SurveyPage(content="在过去的4周内，你是否看了医生并得到你的处方药可定？", choices=["否", "是"], nextIds=[str(surveyPage1b.id), str(surveyPage1a.id)]).save()

    db_engine.Survey(firstNode=str(surveyPage1.id), name="DoTQ", des="", surveies=[surveyPage1, surveyPage1a, surveyPage1a1, surveyPage1b, surveyPage1ba, surveyPage1bb, surveyPage1bbb4, surveyPage1bbb3, surveyPage1bbb2, surveyPage1bbb1
    , surveyPage1bbb, surveyPage1bba2, surveyPage1bba1, surveyPage1bba]).save()


def raq():
    connect('az', host=host)

    surveyPage12 = db_engine.SurveyPage(content="您认为服用瑞舒伐他汀药物利大于弊吗？", choices=["不，一点也不这样认为", "是的，利肯定大于弊"], nextIds=[]).save()

    surveyPage11 = db_engine.SurveyPage(content="您是否明白您为什么要服用瑞舒伐他汀药物？", choices=["不，完全不明白", "略知一二", "是，完全明白"], nextIds=[str(surveyPage12.id)]).save()

    surveyPage10 = db_engine.SurveyPage(content="您是否觉得不方便或难以坚持瑞舒伐他汀的服药计划？", choices=["不，一点也不会", "有一点", "是的，非常不方便"], nextIds=[str(surveyPage11.id)]).save()

    surveyPage9 = db_engine.SurveyPage(content="过去您是否忘记过服用瑞舒伐他汀药物？", choices=["不，从不会忘记", "是，经常忘记"], nextIds=[str(surveyPage10.id)]).save()

    surveyPage8 = db_engine.SurveyPage(content="您认为偶尔暂停服用瑞舒伐他汀药物是否对您有害？", choices=["否", "是"], nextIds=[str(surveyPage9.id)]).save()

    surveyPage7 = db_engine.SurveyPage(content="在过去4周中未服用瑞舒伐他汀药物时，您是否经常故意不服用瑞舒伐他汀药物？", choices=["从不", "有时", "经常"], nextIds=[str(surveyPage8.id)]).save()

    surveyPage6 = db_engine.SurveyPage(content="在过去4周中未服用瑞舒伐他汀药物时，您是否经常是由于忘记而没有服用瑞舒伐他汀药物？", choices=["从不", "有时", "经常"], nextIds=[str(surveyPage7.id)]).save()

    surveyPage5 = db_engine.SurveyPage(content="过去4周中，您共服用了多少天的瑞舒伐他汀药物？", choices=[0, 27], type=2, nextIds=[str(surveyPage6.id)]).save()

    surveyPage4 = db_engine.SurveyPage(content="在过去4周中，您是否每天服用瑞舒伐他汀？", choices=["否", "是"], nextIds=[str(surveyPage5.id), str(surveyPage8.id)]).save()

    surveyPage3 = db_engine.SurveyPage(content="最近一次访视时，您获得的处方包含多少天的瑞舒伐他汀治疗？", choices=[1, 28],type=2, nextIds=[str(surveyPage4.id)]).save()


    surveyPage2 = db_engine.SurveyPage(content="您最近一次就诊并获得瑞舒伐他汀处方是什么时候？", choices=[], type=1,  nextIds=[str(surveyPage3.id)]).save()

    #raq 1
    surveyPage1 = db_engine.SurveyPage(content="您在过去4周内是否看过医生，并获得瑞舒伐他汀处方？", choices=["否", "是"], nextIds=[str(surveyPage4.id), str(surveyPage2.id)]).save()

    db_engine.Survey(firstNode=str(surveyPage1.id), name="RAQ", des="瑞舒伐他汀依从性调查问卷", surveies=[surveyPage1, surveyPage2, surveyPage3, surveyPage4, surveyPage5, surveyPage6,
                                                                                              surveyPage7, surveyPage8, surveyPage9, surveyPage10, surveyPage11, surveyPage12]).save()
def scheduleTask():
    debuggerLogger = logging.getLogger('survey')
    debuggerLogger.setLevel(logging.DEBUG)
    debuggerLogger.addHandler(handler)
    debuggerLogger.debug('scheduleTask start')
    checkSurveySchedule()

def scheduleNoMsgTask():
    debuggerLogger = logging.getLogger('survey')
    debuggerLogger.setLevel(logging.DEBUG)
    debuggerLogger.addHandler(handler)
    debuggerLogger.debug('scheduleNoMsgTask start')
    checkSurveySchedule(needSendMsg=False)

if __name__ == "__main__":
    # print querySurveySchedule('18001822249').currentSurvey
    # updateSurveySchedule('18001822249', 'BMQ-G')
    # bmqg()
    # lsqv1()
    # lsqv2()
    # raq()
    logger.info('start schedule')
    schedule.every().minutes.do(scheduleNoMsgTask)
    schedule.every().day.at("08:00").do(scheduleTask)
    schedule.every().day.at("20:00").do(scheduleNoMsgTask)

    while 1:
        schedule.run_pending()
        time.sleep(1)

    # scheduleTask()

    # scheduleNoMsgTask()
    # checkSurveySchedule(needSendMsg=False)